﻿using RTW.DAL;
using RTW.OA.Areas.Personal.Models;
using RTW.OA.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RTW.OA.Areas.Personal.Servers
{
    public class EMailServers
    {
        private readonly IRepository<email_body> email_bodyRepository;
        private readonly IRepository<email> email_Repository;
        private readonly IRepository<email_box> email_boxRepository;

        public EMailServers()
        {
            email_bodyRepository = new DapperRepository<email_body>();
            email_Repository = new DapperRepository<email>();
            email_boxRepository = new DapperRepository<email_box>();
        }

        public List<EmailForBox> GetData(string search,string boxClass)
        {
            var arrTemp = " where 1=1 ";
            var sql = "select * from email e left join email_body b on e.BODY_ID=b.BODY_ID ";
            if (!string.IsNullOrWhiteSpace(boxClass))
            {
                if (boxClass == "4")
                {
                    arrTemp += " and (e.DELETE_FLAG = 2 or e.DELETE_FLAG =3)  ";
                }
                else
                {
                    arrTemp += " and (e.DELETE_FLAG = 0 or e.DELETE_FLAG is null) ";
                }
            }
            else
            {
                arrTemp += " and (e.DELETE_FLAG = 0 or e.DELETE_FLAG is null) ";
            }
            sql += arrTemp;
            if (!string.IsNullOrEmpty(search))
            {
                sql += " and b.SUBJECT like '%"+search+"%' or b.CONTENT like '%"+search+"%'";
            }
            if (!string.IsNullOrWhiteSpace(boxClass))
            {
                sql += " and e.BOX_ID = @boxClass";
            }
            var datas = email_bodyRepository.SqlWithParamsDynamic(sql, new {  boxClass = boxClass });
                return AutoMapper.Mapper.Map<List<EmailForBox>>(datas);
        }

        public email_body GetModelById(string id)
        {
             var data = email_bodyRepository.GetById(id);
             return data;  
        }


        internal void Add(email_body model, string type, string UserId)
        {
            email email = new email();

            //type send 发送  drafts 草稿箱
            if (type == "send")
            {
                //发送时，新增两条  收件人 发件人
                #region 发送端
                model.SEND_FLAG = "1";
                model.BODY_ID = GetGuid();
                model.SEND_TIME = DateTime.Now;
                email_bodyRepository.Insert(model);

                email.BODY_ID = model.BODY_ID;
                email.BOX_ID = GetBoxForUserId(UserId, "发件箱");//发件箱
                email.COPY_ID = model.COPY_TO_ID;
                email.IS_R = 0;//未回复
                email.READ_FLAG = 0;//未读
                email.TO_ID = model.TO_ID2;
                email.DELETE_FLAG = 0;//删除状态
                email_Repository.Insert(email);
                #endregion

                #region 接收端
                model.SEND_FLAG =null;
                model.BODY_ID = GetGuid();
                model.SEND_TIME = null;
                email_bodyRepository.Insert(model);

                email.BODY_ID = model.BODY_ID;
                email.BOX_ID = GetBoxForUserId(UserId, "收件箱");//发件箱
                email.COPY_ID = model.COPY_TO_ID;
                email.IS_R = 0;//未回复
                email.READ_FLAG = 0;//未读
                email.TO_ID = model.TO_ID2;
                email.DELETE_FLAG = 0;//删除状态
                email_Repository.Insert(email);
                #endregion
            }
            else if(type== "drafts")
            {
                model.BODY_ID = GetGuid();
                email_bodyRepository.Insert(model);

                email.BODY_ID = model.BODY_ID;
                email.BOX_ID = GetBoxForUserId(UserId, "草稿箱");//草稿箱
                email.COPY_ID = model.COPY_TO_ID;
                email.IS_R = 0;//未回复
                email.READ_FLAG = 0;//未读
                email.TO_ID = model.TO_ID2;
                email.DELETE_FLAG = 0;
                email_Repository.Insert(email);
            }
        }

        internal void Update(email_body model,string type,string UserId)
        {
            email email = new email();
            var datas = email_Repository.GetAllEnumerable().Where(m=>m.BODY_ID==model.BODY_ID);
            email = datas.First();

            //type send 发送  drafts 草稿箱
            if (type == "send")
            {
                #region 发送端
                model.SEND_FLAG = "1";
                model.SEND_TIME =DateTime.Now;

                email_bodyRepository.Update(model);

                email.BOX_ID = GetBoxForUserId(UserId, "发件箱");//发件箱
                email.COPY_ID = model.COPY_TO_ID;
                email.TO_ID = model.TO_ID2;
                email_Repository.Update(email);
                #endregion

                #region 接收端
                model.BODY_ID = GetGuid();
                model.SEND_FLAG = null;
                model.SEND_TIME = null;

                email_bodyRepository.Insert(model);

                email.BODY_ID = model.BODY_ID;
                email.BOX_ID = GetBoxForUserId(UserId, "收件箱");//发件箱
                email.COPY_ID = model.COPY_TO_ID;
                email.TO_ID = model.TO_ID2;
                email_Repository.Insert(email);
                #endregion

            }
            else if (type == "drafts")
            {
                email_bodyRepository.Update(model);

                email.BOX_ID = GetBoxForUserId(UserId, "草稿箱");//草稿箱
                email.COPY_ID = model.COPY_TO_ID;
                email.TO_ID = model.TO_ID2;
                email_Repository.Update(email);
            }
        }

        internal void Del(string id,string boxclass,string UserId)
        {
            email email = new email();
            var datas = email_Repository.GetAllEnumerable().Where(m => m.BODY_ID == id);
            email = datas.First();

            #region 获取model 更新DELETE_FLAG字段
            var model= GetModelById(id);//email_body
            // 邮件删除状态(0-未删除;1-收件人永久删除;2-发件人删除;3-收件人删除;4-二次删除)
            if (boxclass=="1")//收件箱
            {
                email.DELETE_FLAG = 3;
                email.BOX_ID = 4;
                email_Repository.Update(email);
            }
            else if(boxclass=="2")//发件箱
            {
                email.DELETE_FLAG = 2;
                email.BOX_ID = 4;
                email_Repository.Update(email);
            }
            else if (boxclass=="3")//草稿箱
            {
                email.DELETE_FLAG = 2;
                email.BOX_ID = 4;
                email_Repository.Update(email);
            }
            else if (boxclass=="4")//垃圾箱
            {
                email.DELETE_FLAG = 4;
                email.BOX_ID = 4;
                email_Repository.Update(email);
            }
            #endregion
        }

        internal List<SelectListItem> GetTYPE_ID()
        {
            List<SelectListItem> tables = new List<SelectListItem>();
            var dstable = email_bodyRepository.SqlWithParamsDynamic("select CODE_NO Value, concat(CODE_NO, '-----', CODE_NAME) Text  from[dbo].[sys_code] where PARENT_NO = 166");
            tables.Clear();

            foreach (var dr in dstable)
            {
                string Id = dr.Value.ToString();
                string Title = dr.Text.ToString().Trim();
                tables.Add(new SelectListItem { Value = Id, Text = Title });
            }
            return tables;
        }

        internal string GetGuid()
        {
            return Guid.NewGuid().ToString("N");
        }

        /// <summary>
        /// 根据用户Id和邮箱分类查询Id
        /// </summary>
        /// <returns></returns>
        internal int? GetBoxForUserId(string UserId,string boxName)
        {
            //var boxId = email_bodyRepository.SqlWithParamsDynamic("select BOX_ID from email_box where USER_ID='" + UserId+"'  and BOX_NAME='"+boxName+"'");
            var boxId = email_boxRepository.SqlWithParamsSingle("select BOX_ID from email_box where  BOX_NAME='" + boxName+"'").BOX_ID;

            return Convert.ToInt32(boxId);
        }

        /// <summary>
        /// 根据用户Id查询邮箱分类
        /// </summary>
        /// <returns></returns>
        internal  dynamic GetBoxForUserIdToList(string UserId,string boxclass)
        {
            DataTable dt = new DataTable();

            dynamic dstable;

            var sql = "select a.BOX_ID,a.BOX_NAME,count(b.BOX_ID) as count  from email_box as a left join email as b on a.BOX_ID = b.BOX_ID where b.DELETE_FLAG != 4 or b.DELETE_FLAG is null group by a.BOX_ID, a.BOX_NAME";
               dstable =email_bodyRepository.SqlWithParamsDynamic(sql);

            return dstable;
        }

        /// <summary>
        /// 根据Id获取当前数据所属邮箱分类
        /// </summary>
        internal string GetBoxClassForId(string Id)
        {
            var boxClass = email_boxRepository.SqlWithParamsSingle("select a.BOX_NAME from email_box as a inner join email as b on a.BOX_ID=b.BOX_ID where b.BODY_ID = '" + Id+"'").BOX_NAME;
            return boxClass;
        }
    }
}